#include <botan/base64.h>
#include <botan/hash.h>
#include <botan/symkey.h>
#include <users/user.h>
#include <utils/functions.h>

namespace users {
user::user() {}

user::user(const std::string& line) {
	auto data = utils::split(line, ";");
	_login = data[0];
	_salt = data[1];
	_cipher_algorithm_ = utils::createAlgos(data[2]);
	_hashedPassword = Botan::secure_vector<uint8_t>(data[3].begin(), data[3].end());
	_dataPath = data[4];
	_totpPath = data[5];
}

void user::setHashedPassword(const std::string &hashedPassword) {
	_hashedPassword = Botan::secure_vector<uint8_t>(hashedPassword.begin(), hashedPassword.end());
}

void user::setHashedPassword(const Botan::secure_vector<uint8_t> &hashedPassword) {
	_hashedPassword = hashedPassword;
}

std::string user::getHash() const {
	std::string res(_hashedPassword.begin(), _hashedPassword.end());
	return res;
}

bool user::compare_hashes(const Botan::secure_vector<uint8_t> &hash1) const {
	if (hash1.empty() || hash1.size() != _hashedPassword.size())
		return false;
	return Botan::same_mem(hash1.data(), _hashedPassword.data(), _hashedPassword.size());
}

Botan::SymmetricKey user::generatePass() const {
	auto hash = Botan::base64_encode(_hashedPassword.data(), _hashedPassword.size());
	auto temp = utils::generateSymmetricKeyFromPassword(_salt+hash,32);
	auto tempstr = Botan::base64_encode(temp.data(), temp.size());
	auto res = Botan::SymmetricKey(utils::generateSymmetricKeyFromPassword(tempstr,32));
	return res;
}


std::string to_string(const user &user) {
	std::string res;
	res = user._login + ";";
	res += user._salt + ";";
	res += createStringFromAlgos(user._cipher_algorithm_) + ";";
	res += user.getHash() + ";";
	res += user._dataPath.string() + ";";
	res += user._totpPath.string() + ";";

	return res;
}
}